<template>
  <div class="config-panel">
    <!-- 控制按钮 -->
    <section class="control-section">
      <div class="button-group">
        <button 
          @click="handleConnect" 
          :disabled="isConnecting || appState.avatar.connected"
          class="btn btn-primary"
        >
          {{ isConnecting ? '连接中...' : appState.avatar.connected ? '已连接' : '连接' }}
        </button>
        
        <button 
          @click="handleDisconnect" 
          :disabled="!appState.avatar.connected"
          class="btn btn-secondary"
        >
          断开
        </button>
        
        <button 
          @click="handleOpenConfig" 
          class="btn btn-config"
        >
          设置
        </button>
      </div>
    </section>
    
    <!-- 配置对话框 -->
    <ConfigDialog 
      v-model="showConfigDialog" 
      :app-state="appState" 
      @save="handleSaveConfig"
    />

    <!-- 面试控制 -->
    <section class="interview-control-section">
      <h3 class="section-title">AI 面试官</h3>
      
      <div class="interview-stats">
        <div class="stat-item">
          <span class="stat-label">当前问题:</span>
          <span class="stat-value">{{ currentQuestionInfo }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">状态:</span>
          <span class="stat-value status-{{ interviewStatus }}">{{ interviewStatusText }}</span>
        </div>
      </div>
      
      <div v-if="appState.interview.isStarted" class="timer-section">
        <div class="timer-item" :class="{ 'warning': appState.interview.thinkingTimeLeft < 3 }">
          <span class="timer-label">思考时间:</span>
          <span class="timer-value">{{ formatTime(appState.interview.thinkingTimeLeft) }}</span>
        </div>
        <div class="timer-item" :class="{ 'warning': appState.interview.answerTimeLeft < 10 }">
          <span class="timer-label">回答时间:</span>
          <span class="timer-value">{{ formatTime(appState.interview.answerTimeLeft) }}</span>
        </div>
      </div>
      
      <div class="button-group">
        <button 
          @click="handleStartInterview" 
          :disabled="!appState.avatar.connected || isInterviewing"
          class="btn btn-interview"
        >
          开始面试
        </button>
        
        <button 
          @click="handleEndInterview" 
          :disabled="!appState.interview.isStarted"
          class="btn btn-secondary"
        >
          结束面试
        </button>
        
        <button 
          @click="handleResetInterview" 
          class="btn btn-secondary"
        >
          重置面试
        </button>
      </div>
    </section>

    <!-- 回答输入区域 -->
    <section v-if="appState.interview.isStarted && !appState.interview.isFinished" class="answer-section">
      <h3 class="section-title">你的回答</h3>
      
      <div class="form-group">
        <label>文字回答</label>
        <textarea 
          v-model="answerText" 
          rows="5" 
          placeholder="请输入你的回答..."
          :disabled="!appState.interview.isAnswering"
        />
      </div>
      
      <div class="button-group">
        <button 
          @click="handleVoiceAnswer" 
          :disabled="!appState.avatar.connected || appState.asr.isListening || !appState.interview.isAnswering"
          class="btn btn-voice"
        >
          {{ appState.asr.isListening ? '正在听...' : '语音回答' }}
        </button>
        
        <button 
          @click="handleAnswerComplete" 
          :disabled="!appState.interview.isAnswering"
          class="btn btn-primary"
        >
          回答完毕
        </button>
      </div>
    </section>

    <!-- 面试结果 -->
    <section v-if="appState.interview.isFinished" class="result-section">
      <h3 class="section-title">面试结果</h3>
      
      <div class="score-overview">
        <div class="total-score">
          <span class="score-label">总分:</span>
          <span class="score-value">{{ appState.interview.scores?.total || 0 }}</span>
        </div>
      </div>
      
      <div class="score-details">
        <div class="score-item">
          <span class="score-label">内容质量:</span>
          <span class="score-value">{{ appState.interview.scores?.content || 0 }}</span>
        </div>
        <div class="score-item">
          <span class="score-label">沟通表达:</span>
          <span class="score-value">{{ appState.interview.scores?.communication || 0 }}</span>
        </div>
        <div class="score-item">
          <span class="score-label">逻辑思维:</span>
          <span class="score-value">{{ appState.interview.scores?.logic || 0 }}</span>
        </div>
        <div class="score-item">
          <span class="score-label">自信程度:</span>
          <span class="score-value">{{ appState.interview.scores?.confidence || 0 }}</span>
        </div>
      </div>
      
      <div class="interview-tips">
        <h4>面试建议:</h4>
        <ul>
          <li v-if="appState.interview.scores && appState.interview.scores.content < 70">建议在回答问题时提供更详细的内容和具体案例</li>
          <li v-if="appState.interview.scores && appState.interview.scores.communication < 70">建议提高表达的流畅度和清晰度</li>
          <li v-if="appState.interview.scores && appState.interview.scores.logic < 70">建议在回答时加强逻辑结构，使用总分总等结构</li>
          <li v-if="appState.interview.scores && appState.interview.scores.confidence < 70">建议增强自信心，保持适当的语速和音量</li>
          <li v-if="allScoresAbove70">整体表现优秀，继续保持！</li>
        </ul>
      </div>
    </section>

    <!-- 面试问题列表（仅在面试结束后显示） -->
    <section v-if="appState.interview.isFinished" class="questions-section">
      <h3 class="section-title">面试问题列表</h3>
      
      <div class="questions-list">
        <div 
          v-for="(question, index) in appState.interview.questions" 
          :key="question.id"
          class="question-item completed"
        >
          <div class="question-number">{{ index + 1 }}</div>
          <div class="question-content">
            <div class="question-text">{{ question.question }}</div>
            <div class="question-category">{{ question.category }}</div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { inject, ref, computed, onMounted } from 'vue'
import { useAsr } from '../composables/useAsr'
import { SUPPORTED_LLM_MODELS } from '../constants'
import type { AppState, AppStore } from '../types'
import ConfigDialog from './ConfigDialog.vue'

// 注入全局状态和方法
const appState = inject<AppState>('appState')!
const appStore = inject<AppStore>('appStore')!

// 组件状态
const isConnecting = ref(false)
const isInterviewing = ref(false)
const answerText = ref('')
const showConfigDialog = ref(false)

// 首次进入时检查是否需要显示配置对话框
onMounted(() => {
  // 检查是否已保存配置
  const hasConfig = 
    appState.avatar.appId && appState.avatar.appSecret && 
    appState.asr.appId && appState.asr.secretId && appState.asr.secretKey && 
    appState.llm.apiKey;
  
  // 如果没有配置，显示配置对话框
  if (!hasConfig) {
    showConfigDialog.value = true;
  }
})

// 计算属性
const interviewStatus = computed(() => {
  const { isThinking, isAnswering, isStarted, isFinished } = appState.interview
  if (isFinished) return 'finished'
  if (isThinking) return 'thinking'
  if (isAnswering) return 'answering'
  if (isStarted) return 'started'
  return 'idle'
})

const interviewStatusText = computed(() => {
  switch (interviewStatus.value) {
    case 'thinking': return '思考中'
    case 'answering': return '回答中'
    case 'started': return '进行中'
    case 'finished': return '已结束'
    default: return '未开始'
  }
})

const currentQuestionInfo = computed(() => {
  const { currentQuestionIndex, questions } = appState.interview
  if (currentQuestionIndex < questions.length) {
    const question = questions[currentQuestionIndex]
    return `${currentQuestionIndex + 1}/${questions.length} (${question.category})`
  }
  return `${questions.length}/${questions.length} (已完成)`
})

const allScoresAbove70 = computed(() => {
  const scores = appState.interview.scores
  if (!scores) return false
  return scores.content >= 70 && scores.communication >= 70 && scores.logic >= 70 && scores.confidence >= 70
})

// 格式化时间
function formatTime(seconds: number): string {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 语音回答处理
async function handleVoiceAnswer() {
  // 验证ASR配置
  const { appId, secretId, secretKey } = appState.asr
  if (!appId || !secretId || !secretKey) {
    alert('请先配置ASR信息（App ID、Secret ID、Secret Key）')
    return
  }
  
  // 创建ASR实例
  const { start: startAsrWithConfig } = useAsr({
    provider: 'tx',
    appId: appState.asr.appId,
    secretId: appState.asr.secretId,
    secretKey: appState.asr.secretKey
  })
  
  appStore.startVoiceInput()
  
  startAsrWithConfig({
    onFinished: (text: string) => {
      answerText.value += text + ' '
      appStore.stopVoiceInput()
    },
    onError: (error: any) => {
      console.error('语音识别错误:', error)
      appStore.stopVoiceInput()
    }
  })
}

// 回答完毕处理
async function handleAnswerComplete() {
  if (!answerText.value.trim()) {
    // 确认是否提交空回答
    if (!confirm('你的回答为空，确定要提交吗？')) {
      return
    }
  }
  
  // 记录回答
  const answerDuration = 120 - appState.interview.answerTimeLeft
  appStore.recordAnswer(answerText.value, answerDuration)
  
  // 重置回答文本
  answerText.value = ''
  
  // 进入下一个问题
  appState.interview.isAnswering = false
  appState.interview.currentQuestionIndex++
  await appStore.nextQuestion()
}

// 事件处理函数
async function handleConnect() {
  if (isConnecting.value) return
  
  isConnecting.value = true
  try {
    await appStore.connectAvatar()
  } catch (error) {
    console.error('连接失败:', error)
    alert('连接失败，请检查配置信息')
  } finally {
    isConnecting.value = false
  }
}

function handleDisconnect() {
  appStore.disconnectAvatar()
}

async function handleStartInterview() {
  isInterviewing.value = true
  try {
    await appStore.startInterview()
  } catch (error) {
    console.error('开始面试失败:', error)
    alert('开始面试失败，请检查配置信息')
  } finally {
    isInterviewing.value = false
  }
}

async function handleEndInterview() {
  try {
    await appStore.endInterview()
  } catch (error) {
    console.error('结束面试失败:', error)
    alert('结束面试失败')
  }
}

function handleResetInterview() {
  appStore.resetInterview()
  answerText.value = ''
}

// 打开配置对话框
function handleOpenConfig() {
  showConfigDialog.value = true
}

// 保存配置
function handleSaveConfig(config: any) {
  // 更新应用状态
  if (config.avatar) {
    appState.avatar.appId = config.avatar.appId || ''
    appState.avatar.appSecret = config.avatar.appSecret || ''
  }
  
  if (config.asr) {
    appState.asr.provider = config.asr.provider || 'tx'
    appState.asr.appId = config.asr.appId || ''
    appState.asr.secretId = config.asr.secretId || ''
    appState.asr.secretKey = config.asr.secretKey || ''
  }
  
  if (config.llm) {
    appState.llm.model = config.llm.model || SUPPORTED_LLM_MODELS[0]
    appState.llm.apiKey = config.llm.apiKey || ''
  }
  
  // 可以在这里添加本地存储逻辑，保存配置到localStorage
  localStorage.setItem('interviewConfig', JSON.stringify({
    avatar: appState.avatar,
    asr: appState.asr,
    llm: appState.llm
  }))
}
</script>

<style scoped>
.config-panel {
  width: 420px;
  max-height: 100vh;
  overflow-y: auto;
  padding: 24px;
  background: #ffffff;
  border-left: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.config-section,
.control-section,
.interview-control-section,
.result-section,
.questions-section {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 8px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group:last-child {
  margin-bottom: 0;
}

label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #555;
}

input,
select,
textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
}

input:focus,
select:focus,
textarea:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

textarea {
  resize: vertical;
  min-height: 80px;
}

.button-group {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 80px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #0056b3;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background: #545b62;
}

.btn-interview {
  background: #28a745;
  color: white;
}

.btn-interview:hover:not(:disabled) {
  background: #1e7e34;
}

.btn-config {
  background: #17a2b8;
  color: white;
}

.btn-config:hover:not(:disabled) {
  background: #138496;
}

/* 面试统计 */
.interview-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.stat-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.status-thinking {
  color: #ffc107;
}

.status-answering {
  color: #28a745;
}

.status-started {
  color: #007bff;
}

.status-finished {
  color: #6c757d;
}

/* 计时器样式 */
.timer-section {
  display: flex;
  gap: 16px;
  margin: 16px 0;
  padding: 12px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #e0e0e0;
}

.timer-item {
  flex: 1;
  text-align: center;
}

.timer-label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.timer-value {
  display: block;
  font-size: 24px;
  font-weight: 700;
  color: #333;
}

.timer-item.warning .timer-value {
  color: #dc3545;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0.5; }
}

/* 面试结果样式 */
.score-overview {
  text-align: center;
  margin-bottom: 16px;
}

.total-score {
  display: inline-block;
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 50%;
  width: 120px;
  height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
}

.score-label {
  font-size: 14px;
  font-weight: 500;
}

.score-value {
  font-size: 36px;
  font-weight: 700;
  line-height: 1;
}

.score-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 16px;
}

.score-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #e0e0e0;
}

.score-item .score-value {
  font-size: 20px;
  margin-top: 4px;
}

.interview-tips {
  background: #fff3cd;
  border: 1px solid #ffeeba;
  border-radius: 6px;
  padding: 12px;
}

.interview-tips h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #856404;
  font-weight: 600;
}

.interview-tips ul {
  margin: 0;
  padding-left: 20px;
}

.interview-tips li {
  font-size: 13px;
  color: #856404;
  margin-bottom: 4px;
  line-height: 1.4;
}

/* 问题列表样式 */
.questions-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.question-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  transition: all 0.2s;
}

.question-item:hover {
  border-color: #007bff;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.1);
}

.question-item.active {
  border-color: #28a745;
  background: #f0fff4;
  box-shadow: 0 2px 8px rgba(40, 167, 69, 0.1);
}

.question-item.completed {
  border-color: #6c757d;
  background: #f8f9fa;
  opacity: 0.8;
}

.question-number {
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #007bff;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}

.question-item.active .question-number {
  background: #28a745;
}

.question-item.completed .question-number {
  background: #6c757d;
}

.question-content {
  flex: 1;
  min-width: 0;
}

.question-text {
  font-size: 13px;
  color: #333;
  line-height: 1.4;
  margin-bottom: 4px;
  word-break: break-word;
}

.question-category {
  font-size: 11px;
  color: #666;
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

/* 滚动条美化 */
.config-panel::-webkit-scrollbar,
.questions-list::-webkit-scrollbar {
  width: 6px;
}

.config-panel::-webkit-scrollbar-track,
.questions-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.config-panel::-webkit-scrollbar-thumb,
.questions-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.config-panel::-webkit-scrollbar-thumb:hover,
.questions-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
